//
//  MSNewFeatureView.swift
//  SwiftWeibo
//
//  Created by 824810056 on 16/8/16.
//  Copyright © 2016年 DoNews. All rights reserved.
//

import UIKit

class MSNewFeatureView: UIView {

    
    @IBOutlet weak var scrollView: UIScrollView!
    
    @IBOutlet weak var startButton: UIButton!
    
    @IBOutlet weak var pageControl: UIPageControl!
    
    class func newFeatureView() -> MSNewFeatureView{
        
        let nib = UINib(nibName: "MSNewFeatureView", bundle: nil)
        
        let view = nib.instantiate(withOwner: nil, options: nil)[0] as! MSNewFeatureView
        
        view.frame = UIScreen.main.bounds
        
        view.backgroundColor = UIColor.clear
        
        return view
   
    }
    
    override func awakeFromNib() {
        
        
        
        let screenWidth = UIScreen.main.bounds.width
        let screenHeight = UIScreen.main.bounds.height
        
        let count = 4
        for i in 0..<4 {
            let imageView = UIImageView(image: UIImage(named: "new_feature_\(i+1)"))
            
            imageView.frame = CGRect(x: CGFloat(i) * screenWidth, y: 0, width: screenWidth, height: screenHeight)
            scrollView.addSubview(imageView)
            
        }
        
        scrollView.contentSize = CGSize(width: (CGFloat(count) + 1.0) * screenWidth, height: screenHeight)
        scrollView.bounces = false
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.isPagingEnabled = true
        scrollView.delegate = self
        
        
        startButton.isHidden = true
        
        
    }
    

}

extension MSNewFeatureView: UIScrollViewDelegate{
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        // 0. 一旦滚动隐藏按钮
        startButton.isHidden = true
        
        // 1. 计算当前的偏移量
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width + 0.5)
        
        // 2. 设置分页控件
        pageControl.currentPage = page
        
        // 3. 分页控件的隐藏
        pageControl.isHidden = (page == scrollView.subviews.count)
    }
    
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
        // 1. 滚动到最后一屏，让视图删除
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        
        // 2. 判断是否最后一页
        if page == scrollView.subviews.count {
            
            removeFromSuperview()
        }
        
        // 3. 如果是倒数第2页，显示按钮
        startButton.isHidden = (page != scrollView.subviews.count - 1)
    }
    
}
